<script setup lang="ts">
import { getPublicKey, loginUser, refreshToken, schoolCASLoginUser } from '@/api/login/userLogin';
import { useUserStore } from '@/stores/useUserStore';
import { Spin, message } from 'ant-design-vue';
import { JSEncrypt } from 'jsencrypt';
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const userStore = useUserStore();

const VITE_BUPT_AUTH = import.meta.env.VITE_BUPT_AUTH
const username = ref('');
const password = ref('');
const error = ref('');
const loading = ref(false);
const isInitialized = ref(false);
const router = useRouter();
const route = useRoute();
// 从路由中获取ticket参数
const ticket = ref<string>(route.query.ticket as string)

// Retrieve the redirect path from query parameters or set a default
const redirectPath = ref<string>(route.query.redirect as string || '/user/homepagesquare');

// eslint-disable-next-line no-console
console.log('redirectPath: ', redirectPath.value)

const successLogin = (response: any) => {
  router.push({ path: redirectPath.value });
  message.success('登录成功');

  // 获取用户信息
  userStore.setUserInfo();
  userStore.setIsTeacher();
}

const casAutoLogin = async () => {
  if (ticket.value) {
    try {
      // 需要移除的参数列表
      const removeParams = ['ticket']

      // 获取当前URL的参数对象
      const urlSearchParams = new URLSearchParams(window.location.search)

      // 移除指定参数
      removeParams.forEach(param => urlSearchParams.delete(param))

      // 重新构建search字符串
      const newSearch = urlSearchParams.toString()

      // 构建新的路径
      let currentPath = window.location.pathname
      if (newSearch)
        currentPath += `?${newSearch}`

      // 移除末尾的 ?, & 等符号
      currentPath = currentPath.replace(/[?&]$/, '')

      // 调用登录接口
      const response = await schoolCASLoginUser(ticket.value, currentPath);
      successLogin(response);
    }
    catch (err: any) {
      message.error(`学校CAS登录失败，请稍后再试。`);
      console.error('CAS协议登录失败:', err);
    }
  }
  else {
    // 跳转到统一身份认证登录
    window.location.href = `${VITE_BUPT_AUTH}/login?service=${window.location.href}`;
  }
}

const normalLogin = async () => {
  try {
    const publicKey = await getPublicKey();
    const encrypt = new JSEncrypt();
    encrypt.setPublicKey(publicKey);

    const encryptedPassword = encrypt.encrypt(password.value);

    const response = await loginUser(username.value, encryptedPassword);
    successLogin(response);
  }
  catch (err: any) {
    message.error(`普通登录失败，请稍后再试。`);
    console.error('普通登录失败:', err);
  }
}

const loginType = ref('北邮统一身份'); // Default login type

// Submit Login
const handleSubmit = async () => {
  loading.value = true;
  try {
    // 根据 loginType 调用不同的 API
    if (loginType.value === '北邮统一身份')
      await casAutoLogin();
    else
      await normalLogin();
  }
  catch (err: any) {
    message.error(`登录失败，${err.message}，请稍后再试。`);
    error.value = err.message || '登录失败，请稍后再试。';
  }
  finally {
    loading.value = false;
  }
};

// Switch to School Login
const changLoginType = () => {
  if (loginType.value === '北邮统一身份') {
    loginType.value = '普通方式';
    message.info('切换为普通登录');
    return;
  }
  loginType.value = '北邮统一身份';
  message.info('切换为北邮统一身份登录');
};

// Attempt Auto-Login
onMounted(() => {
  // 登录页面关闭定时刷新计时器
  // authTokenStore.stopTokenRefreshTask()
  loading.value = true;
  // 如果有 ticket，则自动登录
  if (ticket.value) {
    casAutoLogin();
  }
  else {
    refreshToken().then((response) => {
      successLogin(response);
    }).catch((err) => {
      console.error('自动登录失败:', err);
    }).finally(() => {
      loading.value = false;
      isInitialized.value = true;
    });
  }
});
</script>

<template>
  <div v-if="!isInitialized || loading" class="loadingOverlay">
    <Spin size="large" />
  </div>

  <div v-else class="loginContainer">
    <div class="loginBox">
      <div class="loginImage">
        <div class="logoAndText">
          <img src="@/assets/1.jpg" alt="Logo" class="logoImg">
          <h1>智链iLink</h1>
        </div>
        <img src="@/assets/yhtx_dlzc_1.png" alt="iLink" class="mainImg">
      </div>
      <div class="verticalLine" />
      <div class="loginForm">
        <h1>登录</h1>
        <div class="login-type">
          <div style="color:black;font-size: 18px;">
            使用{{ loginType }}认证
          </div>
          <a-button type="link" @click="changLoginType">
            切换登录方式
          </a-button>
        </div>
        <p v-if="error" class="errorMessage">
          {{ error }}
        </p>
        <form @submit.prevent="handleSubmit">
          <div v-if="loginType !== '北邮统一身份'" class="formGroup">
            <label for="username">用户名/邮箱</label>
            <input
              id="username"
              v-model="username"
              type="text"
              placeholder="请输入用户名/邮箱"
              required
            >
          </div>
          <div v-if="loginType !== '北邮统一身份'" class="formGroup">
            <label for="password">登录密码</label>
            <input
              id="password"
              v-model="password"
              type="password"
              placeholder="请输入登录密码"
              required
            >
          </div>
          <button type="submit" class="loginButton">
            登录
          </button>
        </form>
        <div class="loginLinks">
          <p>
            或者 <a href="/register">注册</a>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
:root {
  font-size: 16px; /* 基准 font-size */
}

/* 独特的命名确保样式隔离 */
.loginContainer {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #FFFFFF;
}

.loginBox {
  display: flex;
  background-color: #fff;
  box-shadow: 0 0 0.625rem #81838F;
  border-radius: 0.5rem;
  overflow: hidden;
  height: 37.5rem;
  width: 68.75rem;
}

.loginImage {
  display: flex;
  flex-direction: column; /* 确保图片纵向排列 */
  padding: 1.25rem;
  height: 28.125rem;
  width: 39.375rem;
  position: relative; /* 为了定位 logo 图片 */
  margin-left: 2rem;
}

.logoAndText {
  display: flex;
  align-items:flex-start;
  margin-top: 1rem; /* 根据需要调整 */
  margin-bottom: 2rem;
}

.logoImg {
  width: 3rem; /* 调整 logo 的宽度 */
  height: auto;
  margin-right: 1rem; /* 调整图片和文字之间的间距 */
}

/* 确保 h1 与 logoImg 在一行显示 */
.logoAndText h1 {
  margin: 0; /* 去除默认的 h1 外边距 */
  font-size: 2rem; /* 根据需要调整字体大小 */
}

.mainImg {
  width: 25.625rem;
  height: 37.5rem;
}

.verticalLine {
  width: 0.0625rem;
  height: 29.375rem;
  background-color: #ccc;
  margin: 1.25rem 0;
  margin-top: 2.8125rem;
  margin-right: 1.75rem; /* 调整此值以控制与右边组件的距离 */
}

.loginForm {
  padding: 1.25rem;
  width: 31.25rem;
}

.loginForm h1 {
  font-size: 2.1875rem;
  margin-bottom: 0.625rem;
  margin-top: 1.5625rem;
}

.loginForm p {
  margin-bottom: 1.65rem;
  margin-top: 0.7rem;
  color: #a1a1a1;
  font-size: 0.8rem;
}

.loginForm a {
  color: #007bff;
  text-decoration: none;
}

.formGroup {
  margin-bottom: 1rem;
  text-align: left;
}

.formGroup label {
  display: block;
  margin-bottom: 0.625rem;
  font-size: 1.125rem;
  color: #6D6C70;
}

.formGroup input {
  font-size: 1rem;
  width: 90%;
  padding: 0.8125rem;
  box-sizing: border-box;
  border: 0.0625rem solid #ccc;
  border-radius: 0.625rem;
  margin-right: 0.0625rem;
  box-shadow: 0 0 0.0625rem #BBBBBB; /* 添加描边 */
  margin-bottom: 0.625rem;
}

.loginButton {
  width: 90%;
  padding: 0.875rem;
  border: none;
  background-color: #6698ff;
  color: #fff;
  font-size: 0.9375rem;
  border-radius: 0.25rem;
  cursor: pointer;
  transition: background-color 0.3s;
}

.loginButton:hover {
  background-color: #0056b3;
}

.loginLinks {
  width: 90%;
  display: flex;
  justify-content: space-between;
  color: #699aff;
  margin-top: 1.25rem;
}

.loginLinks p {
  margin: 0;
}
/* Login.module.css */
.loadingOverlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: white; /* 背景颜色设置为白色 */
  z-index: 1000; /* 使覆盖层处于页面顶层 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-type {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 90%;
  margin-bottom: 1rem;
}
</style>
